using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class Rock : MonoBehaviour
{
    public enum RockStates { HitPlayer,HitEnemy,HitNothing}
    private Rigidbody rb;
    public  RockStates rockStates;
    

    [Header("Basic Settings")]
    public float force;
    public GameObject target;
    public Vector3 direction;
    public int damage;
    public GameObject breakEffect;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        //FlyToTarget();
        //rockStates = RockStates.HitPlayer;
        rb.velocity = Vector3.one;
    }

    // Update is called once per frame
    private void FixedUpdate()
    {
        if (rb.velocity.sqrMagnitude < 1.0f)
        {
            rockStates = RockStates.HitNothing;
        }


    }


    void FlyToTarget()
    {
        if (target == null)
        {
            target = FindObjectOfType<PlayerController>().gameObject;
        }
        direction = target.transform.position - transform.position + Vector3.up;
        direction.Normalize();
        rb.AddForce(direction * force, ForceMode.Impulse);
    }

    private void OnCollisionEnter(Collision collision)
    {
        switch (rockStates)
        {
            case RockStates.HitPlayer:
                if (collision.gameObject.CompareTag("Player"))
                {
                    collision.gameObject.GetComponent<NavMeshAgent>().isStopped = true;
                    collision.gameObject.GetComponent<NavMeshAgent>().velocity = direction * force;

                    collision.gameObject.GetComponent<Animator>().SetTrigger("Dazzy");

                    collision.gameObject.GetComponent<CharacterStats>().TakeDamage(damage, collision.gameObject.GetComponent<CharacterStats>());

                    rockStates = RockStates.HitNothing;
                }
                break;
            case RockStates.HitEnemy:
                if (collision.gameObject.CompareTag("Enemy"))
                {
                    var collisionStats = collision.gameObject.GetComponent<CharacterStats>();
                    collisionStats.TakeDamage(damage, collisionStats);
                    Instantiate(breakEffect, transform.position, Quaternion.identity);
                    Destroy(this.gameObject);
                }
                break;
        }
    }
}
